<?php
/**
 * +----------------------------------------------------------------------+
 * php23种设计模式实现-命令模式
 * Author：微信公众号：yuantanphp
 * 获取更多资源，技术答疑，项目合作请关注微信公众号：yuantanphp
 * +----------------------------------------------------------------------+
 */
//命令接口
interface Command
{
    public function execute();
}
//命令调度者
class Invoker
{
    //命令列表
    private $_command = array();
    //新增命令
    public function addCommand($command)
    {
        $this->_command[] = $command;
    }
    //执行命令
    public function executeCommand()
    {
        foreach ($this->_command as $command) {
            $command->execute();
        }
    }
    //移除命令
    public function removeCommand($command)
    {
        $key = array_search($command, $this->_command);
        if ($key !== false) {
            unset($this->_command[$key]);
        }
    }
}
//生产线接受命令
class workShop
{
    private $_production_line  = null;

    public function __construct($productionLine) {
        $this->_production_line = $productionLine;
    }
 
    public function action()
    {
         echo $this->_production_line." 执行攻击命令开始组装摩托车<br />";
    }
}
//车间主任-分配命令给生产线
class workShopDirector implements Command{
    private $_work_shop;
    public function __construct($_work_shop)
    {
          $this->_work_shop = $_work_shop;
     }
    //执行命令
    public function execute()
    {
        $this->_work_shop->action();
    }
}
$workShopA = new workShop("生产线1");
$workShopB = new workShop("生产线2");
$workShopDirectorA = new workShopDirector($workShopA);
$workShopDirectorB = new workShopDirector($workShopB);

$objInvoker = new Invoker();
$objInvoker->addCommand($workShopDirectorA);
$objInvoker->addCommand($workShopDirectorB);

$objInvoker->executeCommand();
